<?php

namespace app\common\service;



use think\facade\Config;
use app\common\model\system\SysStorage;
use think\Image;

class UploadService
{
    private  string $default;
    private  array $disks;
    private  array $file;

    public function __construct($default = '')
    {
        $config = Config::get('filesystem'); //系统配置
        $this->default = $default ?: $config['default'];
        $this->disks = $config['disks'];
        $this->file = $config['file'];

    }

    /**
     * @notes 上传图片


     */
    public  function image(string $saveDir = 'uploads/images')
    {

            //获取启用的存储配置
            $config =SysStorage::where('status',1)->find()->toArray();
            // 2、执行文件上传
            $StorageDriver =new $this->disks[$this->default]['driver']($config);
            $StorageDriver->setUploadFile('file');
            $fileName = $StorageDriver->getFileName();
            $fileInfo = $StorageDriver->getFileInfo();
				
            $suffixArr = explode('.',$fileInfo['name']);
			$suffix ='.'.strtolower($suffixArr[count($suffixArr) -1]);
            if (!in_array($suffix, explode(',', $this->file['suffix']))) {
                tips('系统不支持' . $suffix . '格式');
            }
            // 上传文件
           
            $pathTime = date('Ymd');
            $saveDir1 = $saveDir . '/' .$pathTime  ;
            $thumbnailDir = 'uploads/thumbnails/'. $pathTime;
            $url = $saveDir1 . '/' . str_replace("\\","/", $fileName);
            if (!$StorageDriver->upload($saveDir1)) {
                tips($StorageDriver->getError());
            }

            $imgArr = ['.png','.jpg','.jpeg'];
            if(in_array($suffix, $imgArr) && $fileInfo['size']>5000){ //创建缩略图
                //图片测生成缩略图
                // 使用ThinkPHP的Image类加载原图
                $image = Image::open($url);
                $yw = $image->width();
                $sb = $yw/150;
                $yh = $image->height();
                $sh =  $yh/$sb;
               
                 if($image->width()>150){
                     if(is_mkdir($thumbnailDir)){
                         
                         $url = $thumbnailDir. '/' . str_replace("\\","/", $fileName);
                         $image->thumb(150, (int) $sh, Image::THUMB_FIXED)->save($url);
                     }
                 }
            }
            // 3、处理文件名称
            if (strlen($fileInfo['name']) > 128) {
                $name = substr($fileInfo['name'], 0, 123);
                $nameEnd = substr($fileInfo['name'], strlen($fileInfo['name'])-5, strlen($fileInfo['name']));
                $fileInfo['name'] = $name . $nameEnd;
            }
            // 4、写入数据库中
           // $url = $saveDir . '/' . str_replace("\\","/", $fileName);

            $res =  ['fileName'=>$fileInfo['name'], 'url' =>  $url,
                'src' => $config['domain']. $url,'suffix'=>$suffix,'size'=>$fileInfo['size']];
            return $res;

    }
    
   


}